from rest_framework import viewsets
from rest_framework.response import Response

from manage.authentication import JWTAuth
from manage.models.system import Permission
from manage.permission import CustomPermission
from manage.serializers.system import PermissionSerializer

# 权限管理
class PermissionViewSet(viewsets.ModelViewSet):
    queryset = Permission.objects.all()
    serializer_class = PermissionSerializer
    # 使用自定义登录认证类验证登录状态
    authentication_classes = (JWTAuth,)
    # 使用自定义权限验证类进行权限验证
    permission_classes = [CustomPermission]

    def list(self, request, *args, **kwargs):
        # 重写 list 不会影响 permission_classes、filter_backends 等，
        # 因为 self.filter_queryset() 和权限检查是在父类方法中自动处理的（但你手动调用 filter_queryset 就能继承这些行为）
        queryset = self.filter_queryset(Permission.objects.filter(parent_id__isnull=True).all())
        serializer = self.get_serializer(queryset, many=True)
        return Response(serializer.data)
